package com.demo.service.impl;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo.enums.DataSourceEnum;
import com.demo.mapper.datasourceB.AdminMapper;
import com.demo.model.datasourceA.User;
import com.demo.model.datasourceB.Admin;
import com.demo.service.AdminService;
import com.demo.service.UserService;
import com.demo.util.CustomerContextHolder;
import com.demo.util.DataSourceB;

@Service
public class AdminServiceImpl implements AdminService {

	@Autowired
	UserService userService;

	@Autowired
	AdminMapper adminMapper;
	
	@Override
//	@Transactional(propagation=Propagation.NESTED)
//	@Transactional(propagation=Propagation.NESTED,rollbackFor={DuplicateKeyException.class})
	public int insertAdmin(Admin record) {
		if (null == record) {
			return 0;
		}
		CustomerContextHolder.setDataSource(DataSourceEnum.DataSourceB);
		return adminMapper.insert(record);
	}

	@Override
	public User selectAdminById(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Admin> selectAllAdmin() {
		// TODO Auto-generated method stub
		return null;
	}

//	@Transactional(value="transactionManagerB")
	private int synUser(List<User> users) {
		int result = 0;
		if (null != users) {
			for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
				User user = iterator.next();
				Admin admin = new Admin();
				admin.setName(user.getName());
//				CustomerContextHolder.setDataSource(DataSourceEnum.DataSourceB);
				result += adminMapper.insert(admin);
//				if (result==3) {
//					throw new RuntimeException();
//				}
				if (result==50) {
					break;
				}
			}
		}
		return result;
	}
	
	public int synUser() {
		return synUser(selectAllUser());
	}
	
	private List<User> selectAllUser() {
		return userService.selectAllUser();
	}


}
